package org.iweb.init.classloader;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"rawtypes","unchecked"})
public class ClassLoaderUtil {

    // Log object
    private static Logger log = LoggerFactory.getLogger(ClassLoaderUtil.class);

    // Parameters
  
	private static final Class[] parameters = new Class[]{URL.class};

    /**
     * Add file to CLASSPATH
     * @param s File name
     * @throws IOException  IOException
     */
    public static void addFile(String s,URLClassLoader sysLoader) throws IOException {
        File f = new File(s);
        addFile(f,sysLoader);
    }

    /**
     * Add file to CLASSPATH
     * @param f  File object
     * @throws IOException IOException
     */
    public static void addFile(File f,URLClassLoader sysLoader) throws IOException {
        addURL(f.toURI().toURL(),sysLoader);
    }

    /**
     * Add URL to CLASSPATH
     * @param u URL
     * @throws IOException IOException
     */
	public static void addURL(URL u,URLClassLoader sysLoader) throws IOException {

    	
    	log.debug(" ADD URL " + u + " to "+sysLoader.toString());
    	
        //URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        URL urls[] = sysLoader.getURLs();
        for (int i = 0; i < urls.length; i++) {
            if (urls[i].toString().equalsIgnoreCase(u.toString())) {
                log.debug("URL " + u + " is already in the CLASSPATH");                
                return;
            }
        }
        Class sysclass = URLClassLoader.class;
        try {
            Method method = sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysLoader, new Object[]{u});
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException("Error, could not add URL to system classloader");
        }
    }

}